<template>
  <div>
    <el-button type="primary" class="addbut" @click="openAddDialog"
      >添加用户<i class="el-icon-circle-plus-outline el-icon--right"></i
    ></el-button>
    <el-table :data="usersData" stripe style="width: 100%">
      <el-table-column prop="username" label="用户名"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column prop="mobile" label="手机号码"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <!-- 状态按钮 -->
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changestate(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <!-- 修改按钮 -->
          <el-button
            type="warning"
            icon="el-icon-edit"
            circle
            @click="showUserEdit(scope.row)"
          ></el-button>
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="removeUserEdit(scope.row)"
          ></el-button>
          <!-- 修改角色按钮 -->
          <el-button
            type="primary"
            icon="el-icon-star-off"
            circle
            @click="showUserRole(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页按钮 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 添加用户弹出框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisibleAdd" width="60%">
      <el-form
        :model="addUserList"
        :rules="rules"
        ref="addUserList"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserList.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserList.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="addUserList.email"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="addUserList.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息弹出框 -->
    <el-dialog title="修改用户信息" :visible.sync="dialogVisible" width="60%">
      <el-form :model="userEditData" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名">
          <el-input v-model="userEditData.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userEditData.email"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="userEditData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUser">确 定</el-button>
        <el-button @click="editcancel">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户角色提示框 -->
    <el-dialog title="修改角色" :visible.sync="dialogFormSole">
      <el-form :model="UserRoleData">
        <el-form-item label="用户名" label-width="100px">
          <el-input
            v-model="UserRoleData.username"
            autocomplete="off"
            class="userinput"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色选择" label-width="100px">
          <el-select v-model="UserRoleData.role_name" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changeRoleCancel">取 消</el-button>
        <el-button type="primary" @click="changeRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      usersData: [],
      pageSize: 5,
      pageNum: 1,
      total: 0,
      dialogVisible: false,
      dialogVisibleAdd: false,
      dialogFormSole: false,
      addUserList: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      userEditData: {},
      UserRoleData: {},
      roleList: [],
    };
  },
  methods: {
    //请求用户列表信息
    async getUserData(pagenum = 1, pagesize = 5) {
      const { data } = await this.$axios.get(
        `/users?pagenum=${pagenum}&pagesize=${pagesize}`
      );
      // console.log(data);
      if (data.meta.status == 200) {
        this.usersData = data.data.users;
        this.total = data.data.total;
      }
    },
    //分页按钮功能
    //每页显示多少条
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getUserData(1, pageSize);
    },
    //当前第几页
    handleCurrentChange(pagenum) {
      this.pageNum = pagenum;
      this.getUserData(pagenum, this.pageSize);
    },
    //打开添加用户对话框
    openAddDialog() {
      this.dialogVisibleAdd = true;
    },
    //添加用户确认
    async addUser() {
      this.dialogVisibleAdd = false;
      const { data } = await this.$axios.post("/users", this.addUserList);
      // console.log(data);
      if (data.meta.status == 201) {
        this.$message({
          type: "success",
          message: data.meta.msg,
        });
        // 添加后刷新
        this.getUserData(1, this.pageSize);
        // 添加后清空表单
        this.addUserList = {};
      } else {
        this.$message.error(data.meta.msg);
      }
    },
    //切换状态
    async changestate(info) {
      const { data } = await this.$axios.put(
        `/users/${info.id}/state/${info.mg_state}`
      );
      // console.log(data);
      if (data.meta.status == 200) {
        this.$message({
          type: "success",
          message: data.meta.msg,
        });
      } else {
        //设置失败把状态还原
        rows.mg_state = !rows.mg_state;
        this.$message.error(data.meta.msg);
      }
    },
    // 修改用户信息
    // 打开弹出框
    showUserEdit(info) {
      this.dialogVisible = true;
      this.userEditData = info;
    },
    // 确认修改
    async editUser() {
      const { data } = await this.$axios.put(
        "/users/" + this.userEditData.id,
        this.userEditData
      );
      if (data.meta.status == 200) {
        this.$message({
          type: "success",
          message: data.meta.msg,
        });
      } else {
        this.$message.error(data.meta.msg);
      }
      this.dialogVisible = false;
    },
    //修改取消事件
    editcancel() {
      this.dialogVisible = false;
      // 重新渲染当前列表还原回去
      this.getUserData(this.pageNum, this.pageSize);
    },
    //删除按钮功能
    removeUserEdit(userinfo) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data } = await this.$axios.delete("/users/" + userinfo.id);
          if (data.meta.status == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //删除更新局部列表
            this.getUserData(this.pageNum, this.pageSize);
          } else {
            this.$message.error(data.meta.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 用户角色按钮
    async showUserRole(userinfo) {
      //打开弹框
      this.dialogFormSole = true;
      this.UserRoleData = userinfo;
      // console.log(this.UserRoleData );
      const { data } = await this.$axios.get("roles");
      // console.log(data.data);
      this.roleList = data.data;
    },
    //修改角色确认
    async changeRole() {
      const { data } = await this.$axios.put(
        `/users/${this.UserRoleData.id}/role`,
        { rid: this.UserRoleData.role_name }
      );
      // console.log(data);
      if (data.meta.status == 200) {
        this.$message({
          type: "success",
          message: data.meta.msg,
        });
        //更新当前页表格
        this.getUserData(this.pageNum, this.pageSize);
      } else {
        this.$message({
          type: "error",
          message: "服务器错误：" + data.meta.msg,
        });
      }
      this.dialogFormSole = false;
    },
    //取消角色分配
    changeRoleCancel(){
      this.dialogFormSole = false;
      // 重新渲染当前列表还原回去
      this.getUserData(this.pageNum, this.pageSize);
    }
  },
  mounted() {
    this.getUserData(1, this.pageSize);
  },
};
</script>

<style>
.addbut {
  float: left;
}
</style>
